﻿Imports System.Data.SqlClient
Public Class FrmDMDonVi

    Dim themmoi As Boolean = True
    Public thanhcong As Boolean = False
    Private Sub FrmDMDonVi_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        UpdateList()
    End Sub

    Private Sub UpdateList(Optional ByVal keyword As String = "")
        Dim strSql As String = "select ROW_NUMBER() OVER (ORDER BY TenDV) as STT, MaDV as [Mã đơn vị], TenDV as [Tên đơn vị], DienGiai as [Diễn giải] from DonVi order by STT"
        Dim myConn As New SqlConnection(chuoiketnoi)
        Dim myTable As New DataTable
        Try
            myConn.Open()
            Dim myAdapter As New SqlDataAdapter(strSql, myConn)
            myAdapter.Fill(myTable)
            dgvList.DataSource = myTable
            dgvList.Columns.Item(0).Width = 50
            dgvList.Columns.Item(1).Visible = False
            dgvList.Columns.Item(2).Width = 100
            dgvList.Columns.Item(3).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
        Catch ex As Exception

        End Try
        myConn.Close()
        myConn.Dispose()
    End Sub

    Private Function DeleteData(ByVal MaDV As String) As Boolean
        Dim strSql As String = "Delete from DonVi where MaDV = @MaDV"
        Dim myConn As New SqlConnection(chuoiketnoi)
        Dim myComm As New SqlCommand
        Dim result As Boolean = True
        Try
            myConn.Open()
            myComm.Connection = myConn
            myComm.CommandText = strSql
            myComm.Parameters.AddWithValue("@MaDV", MaDV)
            myComm.ExecuteNonQuery()
        Catch ex As Exception
            result = False
        End Try
        myConn.Close()
        myConn.Dispose()
        Return result
    End Function

    Private Sub dgvList_KeyDown(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles dgvList.KeyDown
        If e.KeyCode = Keys.Delete Then
            If Me.dgvList.SelectedRows.Count > 0 Then
                If MsgBox("Xóa Đơn vị đã chọn?", MsgBoxStyle.OkCancel, "Xác nhận") = MsgBoxResult.Ok Then
                    If DeleteData(Me.dgvList.SelectedRows.Item(0).Cells(1).Value) Then
                        UpdateList()
                    Else
                        MsgBox("Lỗi xóa dữ liệu!")
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub dgvList_SelectionChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles dgvList.SelectionChanged
        If dgvList.SelectedRows.Count > 0 Then
            txtTenDV.Text = dgvList.SelectedRows(0).Cells(2).Value.ToString()
            txtDienGiai.Text = dgvList.SelectedRows(0).Cells(3).Value.ToString()
        End If
    End Sub

    Private Sub btnThem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnThem.Click
        txtDienGiai.Text = ""
        txtTenDV.Text = ""
        txtDienGiai.ReadOnly = False
        txtTenDV.ReadOnly = False
        btnLuu.Enabled = True
        btnSua.Enabled = False
        themmoi = True
    End Sub

    Private Sub btnXoa_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnXoa.Click
        If Me.dgvList.SelectedRows.Count > 0 Then
            If MsgBox("Xóa Đơn vị đã chọn?", MsgBoxStyle.OkCancel, "Xác nhận") = MsgBoxResult.Ok Then
                If DeleteData(Me.dgvList.SelectedRows.Item(0).Cells(1).Value) Then
                    UpdateList()
                Else
                    MsgBox("Lỗi xóa dữ liệu!")
                End If
            End If
        Else
            MsgBox("Vui lòng chọn dòng cần Xóa!")
        End If
    End Sub

    Private Sub btnSua_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSua.Click
        txtDienGiai.ReadOnly = False
        txtTenDV.ReadOnly = False
        btnLuu.Enabled = True
        themmoi = False
    End Sub

    Private Sub btnDong_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDong.Click
        Me.Close()
    End Sub

    Private Sub btnFirst_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnFirst.Click
        diChuyenChon(1)
    End Sub

    Private Sub btnPrev_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrev.Click
        diChuyenChon(2)
    End Sub

    Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNext.Click
        diChuyenChon(3)
    End Sub

    Private Sub btnLast_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLast.Click
        diChuyenChon(4)
    End Sub

    Private Sub diChuyenChon(ByVal kind As Integer)
        If dgvList.Rows.Count > 0 Then
            Dim curIndex As Integer = 0
            If dgvList.CurrentRow IsNot Nothing Then
                curIndex = dgvList.CurrentRow.Index
            End If
            Select Case kind
                Case 1
                    curIndex = 0
                Case 2
                    If curIndex > 0 Then
                        curIndex = curIndex - 1
                    End If
                Case 3
                    If curIndex <> dgvList.Rows.Count - 1 Then
                        curIndex = curIndex + 1
                    End If
                Case 4
                    curIndex = dgvList.Rows.Count - 1
            End Select
            dgvList.CurrentCell = dgvList.Item(0, curIndex)
        End If
    End Sub

    Private Sub btnHuyBo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnHuyBo.Click
        HuyBo()
        If dgvList.SelectedRows.Count > 0 Then
            txtTenDV.Text = dgvList.SelectedRows(0).Cells(2).Value.ToString()
            txtDienGiai.Text = dgvList.SelectedRows(0).Cells(3).Value.ToString()
        End If
    End Sub

    Private Sub HuyBo()
        txtDienGiai.ReadOnly = True
        txtTenDV.ReadOnly = True
        btnLuu.Enabled = False
        btnSua.Enabled = True
    End Sub

    Private Sub btnLuu_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLuu.Click
        If validateInput() Then
            If CapNhat() Then
                MsgBox("Lưu thành công")
                UpdateList()
                thanhcong = True
                If themmoi Then
                    Me.txtDienGiai.Text = ""
                    Me.txtTenDV.Text = ""
                Else
                    HuyBo()
                End If
            Else
                MsgBox("Lưu thất bại")
            End If
        End If
    End Sub

    Private Function CapNhat() As Boolean
        Dim strSql As String = ""
        Dim myConn As New SqlConnection(chuoiketnoi)
        Dim myComm As New SqlCommand
        Dim result As Boolean = True
        Try
            myConn.Open()
            myComm.Connection = myConn
            If themmoi Then
                strSql = "Insert into DonVi(TenDV, DienGiai) values (@TenDV, @DienGiai)"
            Else
                strSql = "Update DonVi set TenDV = @TenDV, DienGiai = @DienGiai where MaDV = @MaDV"
                myComm.Parameters.AddWithValue("@MaDV", dgvList.SelectedRows(0).Cells(1).Value.ToString())
            End If
            myComm.CommandText = strSql
            myComm.Parameters.AddWithValue("@TenDV", txtTenDV.Text.Trim())
            myComm.Parameters.AddWithValue("@DienGiai", txtDienGiai.Text.Trim())
            myComm.ExecuteNonQuery()
        Catch ex As Exception
            result = False
        End Try
        myConn.Close()
        myConn.Dispose()
        Return result
    End Function

    Private Function validateInput() As Boolean
        If Me.txtTenDV.Text.Trim = "" Then
            MsgBox("Tên đơn vị không thể rỗng.", MsgBoxStyle.Information)
            txtTenDV.Focus()
            Return False
        End If
        Return True
    End Function
End Class